package dk.datainfusion.cprtest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dk.datainfusion.cprtest.model.VejRecord;

@SuppressWarnings("serial")
public class DataloadServlet extends HttpServlet {

	public void init() throws ServletException{

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Set<VejRecord> vejRecords = createDataSetFromFile();
		try {
			//TODO: optimize for batch inserts (PersistenceManager#makePersistentAll)
			for (VejRecord vr : vejRecords){
				pm.makePersistent(vr);
			}
		} finally {
			pm.close();
		}

	}

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{
		res.setContentType("text/html");
        res.getWriter().println("<h2>your data has been loaded (maybe)</h2>");
	}
	
	private Set<VejRecord> createDataSetFromFile(){
		RecordReader reader = new RecordReader();
		Set<VejRecord> vejRecordSet = null;
		try {
			
			//Yes, hard-coded. Want a piece of me?
			File f = new File(getServletContext().getRealPath("/WEB-INF/lib/4353.txt"));
			// Open the file that is the first command line parameter
			FileInputStream fstream = new FileInputStream(f);
			// Get the object of DataInputStream
			vejRecordSet = reader.readRecordsFromStream(fstream);

		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return vejRecordSet;
	}
	
}
